package com.cc

import android.animation.Animator
import android.animation.ValueAnimator
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator

class DefaultDanmuAnimator : DanmuAnimator {
    var isRevert = false
    override fun update(danmuEngine: DanmuEngine, danmuMessage: DanmuMessage, viewGroup: ViewGroup) {
        val view = danmuMessage.contentView!!
        var viewWidth = view.measuredWidth;
        val screenWidth = viewGroup.context.resources.displayMetrics.widthPixels
        if (viewWidth == 0) {
            val mode = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            view.measure(mode, mode)
            viewWidth = view.measuredWidth
        }
        view.translationX = if (isRevert) {
            viewGroup.measuredWidth.toFloat()
        } else {
            (-viewWidth).toFloat()
        }
        val x = if (isRevert) {
            -(screenWidth + viewWidth)
        } else {
            screenWidth + viewWidth
        }
        view.animate().setDuration(5000).setInterpolator(LinearInterpolator())
            .translationX(x.toFloat()).setListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(animation: Animator?) {
                }

                override fun onAnimationEnd(animation: Animator?) {
                    view.clearAnimation()
                    danmuEngine.recycle(danmuMessage)
                }

                override fun onAnimationCancel(animation: Animator?) {

                }

                override fun onAnimationStart(animation: Animator?) {

                }
            }).start()
    }

    lateinit var animator: ValueAnimator
}